import styles from './index.module.scss';
import classNames from 'classnames';
import { useEffect, useRef } from 'react';

interface ITextareaProps
  extends React.DetailedHTMLProps<
    React.TextareaHTMLAttributes<HTMLTextAreaElement>,
    HTMLTextAreaElement
  > {
  className?: string;
  maxLength?: number;
  value?: string;
}

export default function Textarea({
  className,
  value,
  autoFocus = true,
  maxLength = 100, //设置默认值
  ...rest
}: ITextareaProps) {
  const textAreaRef = useRef<HTMLTextAreaElement>(null);

  useEffect(() => {
    textAreaRef.current?.setSelectionRange(-1, -1); //设置光标到最后面 原生写法
  }, []);

  return (
    <div className={styles.root}>
      {/* 文本输入框 */}
      <textarea
        ref={textAreaRef}
        autoFocus={autoFocus}
        className={classNames('textarea', className)}
        {...rest}
        value={value}
        maxLength={maxLength}
      />
      {/* 当前字数/最大允许字数 */}
      <div className="count">
        {/* {1}/{100} */}
        {value?.length}/{maxLength}
      </div>
    </div>
  );
}
